<template>
  <ul class="tabs">
    <li
      class="tab-item"
      v-for="(item, index) in tabs"
      :key="item"
      :class="{'active':modelValue === index}"
      @click="switchItem(index)"
    >
      <span>{{item}}</span>
    </li>
    <div class="active-bar" :style="activeStyle" />
  </ul>
</template>

<script setup>
import {computed} from 'vue'
import useThemeStore from '@/store/theme'
import {TAB_ITEM_WIDTH} from '@/utils/constant'

const ITEM_WIDTH = `${TAB_ITEM_WIDTH}px`
const props = defineProps({
  tabs: {
    type: Array,
    default: () => []
  },
  modelValue: {
    type: Number,
    default: 0
  }
})
const emits = defineEmits(['update:modelValue'])

const themeStore = useThemeStore()

const themeColor = computed(() => themeStore.primaryColor)
const width = computed(() => `${props.tabs.length * TAB_ITEM_WIDTH}px`)
const activeStyle = computed(() => {
  const x = TAB_ITEM_WIDTH * props.modelValue
  return {transform: `translate3d(${x}px, 0, 0)`}
})

// 切换tab
function switchItem(index) {
  emits('update:modelValue', index)
}
</script>

<style lang="less" scoped>
@import '@/assets/style/var.less';

.tabs {
  display: flex;
  position: relative;
  align-items: center;
  width: v-bind(width);
  margin: 0 auto;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  .tab-item {
    position: relative;
    z-index: 10;
    flex: 1;
    height: 30px;
    line-height: 30px;
    text-align: center;
    font-size: 14px;
    color: @color-text-s;
    &.active {
      color: #fff;
    }
  }
  .active-bar {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 9;
    width: v-bind(ITEM_WIDTH);
    height: 30px;
    transition: transform 0.3s;
    border-radius: 5px;
    border-right: none;
    background: v-bind(themeColor) !important;
  }
}
</style>